"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.filterInjectOptions = exports.deInject = exports.doInject = exports.inject = void 0;
const jsdom_1 = require("jsdom");
const { beforeEach, afterEach } = globalThis || global || {};
const inject = (opts) => {
    if (typeof beforeEach !== 'function' || typeof afterEach !== 'function')
        return;
    beforeEach(() => (0, exports.doInject)(opts));
    afterEach(() => (0, exports.deInject)());
};
exports.inject = inject;
const doInject = (opts) => {
    const { beforeInject, afterInject, ...rest } = (0, exports.filterInjectOptions)(opts);
    typeof beforeInject === 'function' && beforeInject(rest);
    const dom = new jsdom_1.JSDOM(rest.html, rest);
    if (globalThis != null) {
        // @ts-ignore DOMWindow type check
        globalThis.window = dom.window;
        globalThis.document = dom.window.document;
    }
    else if (global != null) {
        // @ts-ignore DOMWindow type check
        global['window'] = dom.window;
        global['document'] = dom.window.document;
    }
    typeof afterInject === 'function' && afterInject(dom, rest);
};
exports.doInject = doInject;
const deInject = () => {
    if (globalThis != null) {
        // @ts-ignore operator must be optional.
        delete globalThis.window;
        // @ts-ignore operator must be optional.
        delete globalThis.document;
    }
    else if (global != null) {
        // @ts-ignore operator must be optional.
        delete global['window'];
        // @ts-ignore operator must be optional.
        delete global['document'];
    }
};
exports.deInject = deInject;
const filterInjectOptions = (opts) => {
    if (opts == null) {
        return { html: '<html lang="en"><body></body></html>' };
    }
    if (typeof opts === 'string' || Buffer.isBuffer(opts)) {
        return { html: opts };
    }
    return opts;
};
exports.filterInjectOptions = filterInjectOptions;
